<template>
  <div class="project-task-box">
    <div v-if="isTaskView" class="header-tabs">
      <ul>
        <li class="category-item" :class="{'active-category': taskStatus === 'ALL'}" @click="checkTaskStatus('ALL')">全部</li>
        <li class="category-item" :class="{'active-category': taskStatus === 'WAITING'}" @click="checkTaskStatus('WAITING')">等待</li>
        <li class="category-item" :class="{'active-category': taskStatus === 'RUNNING'}" @click="checkTaskStatus('RUNNING')">运行中</li>
        <li class="category-item" :class="{'active-category': taskStatus === 'STOPPED'}" @click="checkTaskStatus('STOPPED')">停止</li>
        <li class="category-item" :class="{'active-category': taskStatus === 'SUCCEEDED'}" @click="checkTaskStatus('SUCCEEDED')">成功</li>
        <li class="category-item" :class="{'active-category': taskStatus === 'FAILED'}" @click="checkTaskStatus('FAILED')">失败</li>
      </ul>
      <span class="count">共{{totalTask}}个任务</span>
    </div>
    <div class="project-task">
      <div class="task-table">
        <load-data v-show="loadState"></load-data>
        <el-table
          v-show="!loadState"
          :data="taskList"
          style="width: 100%"
          :cell-class-name="spidercellname"
          :header-row-class-name="tableheaderClassName">
          <el-table-column
            label=""
            width="40"
            v-if="taskViewBtn">
            <template slot-scope="scope">
              <div class="spider-box">
                <img v-if="scope.row.jobType == 2" src="@/common/image/spider-icon.png" alt="">
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="isTaskView ? '项目>任务代号' : '代号'"
            :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <div class="table-link">
                <span v-if="isTaskView"><a @click="toProjectDetail(scope.row.projectId)">{{scope.row.projectName}}</a> > #{{scope.row.codeNo}}</span>
                <span v-else>#{{scope.row.codeNo}}</span>
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column
            label="任务名称"
            :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <div class="table-link">
                <span>{{ scope.row.jobName }}</span>
              </div>
            </template>
          </el-table-column> -->
          <el-table-column
            prop="tag"
            label="任务标签"
            width="220"
            @cell-click="cellClickTagfun">
            <template slot="header" slot-scope="scope">
              <el-dropdown trigger="click" @command="handleCommandTag" class="tagdropdown" @visible-change="handleVisibleTag">
                <span class="el-dropdown-link" v-bind:layid="scope.row">
                  <span :class="[{'tag-active-class':dropTagActive},{'tag-all-sele':!tagAllSele}]">任务标签<i class="el-icon-arrow-down el-icon--right"></i></span>
                  <!-- <span :class="{'tag-active-class':dropTagActive}">{{selectTagId?selectTagId:"任务标签"}}<i class="el-icon-arrow-down el-icon--right"></i></span> -->
                </span>
                <el-dropdown-menu class="tag-dropdown" slot="dropdown">
                  <div class="tag-dropdown-box" :class="{'tag-dropdown-boxs':tagListWrap.length>6}">
                    <el-dropdown-item v-for="(item, index) in tagListWrap" :key="index" :class="{'tag-all-bottom':item.jobTag==='全部'&&tagListWrap.length>1}" :command="item.jobTag">{{item.jobTag}}</el-dropdown-item>
                  </div>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
            <template slot-scope="scope">
              <div class="table-link table-link-tag">
                <div class="label-con-modify" v-if="scope.row.jobTag && jobTabModifyindex != scope.$index" @click="jobTabModifyFun(scope.row,scope.$index)">
                  {{scope.row.jobTag}}
                </div>
                <div v-else>
                  <div class="label-con-add" v-if="scope.$index !== selectedLabelIndex && jobTabModifyindex != scope.$index" @click="handlelabelConAdd(scope.$index,scope.row)">
                      +
                  </div>
                  <div class="label-con-box" v-else>
                    <el-input v-model="labelCon" placeholder="" v-focus maxlength="16" @focus="handlelabelFocusCon(scope.row)" @blur="handlelabelBlueCon(scope.row)"></el-input>
                    <!-- <div class="label-con-true" @click="handlelabelConConfirm(scope.row)">√</div> -->
                </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="size"
            label="状态"
            width="110">
            <!-- :render-header="stateScreening" -->
            <template slot="header" slot-scope="scope">
              <el-dropdown v-if="taskViewBtn" trigger="click" @command="handleCommand"  class="statedropdown" @visible-change="handleVisibleState">
                <span class="el-dropdown-link" v-bind:layid="scope.row">
                  <span :class="[{'state-active-class':dropStateActive},{'state-all-sele':!stateAllSele}]">状态<i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <!-- <span :class="{'state-active-class':dropStateActive}">
                     {{selectStateId?selectJobTag:"状态"}}<i class="el-icon-arrow-down el-icon--right"></i>
                  </span> -->
                </span>
                <el-dropdown-menu slot="dropdown" class="state-dropdown">
                  <el-dropdown-item v-for="item in stateAttr" :key="item.id" :command="composeValue(item,scope.row)" :class="{'state-all-bottom':item.jobTag==='全部'}" >{{item.jobTag}}</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <span v-else>状态</span>
            </template>
            <template slot-scope="scope">
              <span class="status-box" :class="[scope.row.statusClass]">{{ scope.row.status }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column
            v-if="!isTaskView"
            prop="size"
            label="任务类型"
            width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.jobType === 1 ? '普通' : '调试' }}</span>
            </template>
          </el-table-column> -->
          <el-table-column
            prop="createTime"
            label="开始时间"
            width="195">
            <template slot-scope="scope">
              <span class="task-time">{{ scope.row.createdTime ? new Date(scope.row.createdTime).Format("yyyy-MM-dd hh:mm:ss") : '--' }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="startTime"
            label="结束时间"
            v-if="taskViewBtn"
            width="185">
            <template slot-scope="scope">
              <span class="task-time">{{ scope.row.completedTime ? new Date(scope.row.completedTime).Format("yyyy-MM-dd hh:mm:ss") : '--'}}</span>
            </template>
          </el-table-column> -->
          <el-table-column
            prop="size"
            width="140"
            label="用时">
            <template slot-scope="scope">
              <span>{{ scope.row.duration }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="size"
            label="操作"
            width="210">
            <template slot-scope="scope">
              <span>
                <el-popover
                  trigger="hover"
                  width="300"
                  :disabled="scope.row.remark?false:true"
                  placement="left">
                  <p class="task-remark-popover">{{ scope.row.remark }}</p>
                  <div slot="reference" class="name-wrapper">
                    <a v-popover:popover1 class="table-action" @click="viewTaskDetail(scope.row)">查看</a>
                  </div>
                </el-popover>
                <a class="table-action" :class="{'table-action-disable': scope.row.showTensorBoardLoding}" @click="toTensorBoard(scope.row)"><i v-show="scope.row.showTensorBoardLoding" class="el-icon-loading" /><span>TensorBoard</span></a>
                <a v-if="scope.row.status === '运行中' || scope.row.status === '等待'" class="table-action" @click="stopTask(scope.row)">停止</a>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="!loadState" class="basePagenate">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :current-page="pageNumber"
          :total="totalTask"
          layout="prev, pager, next">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { getProjectDetail, getTaskViewList, taskOperation, createTensorBoard, saveJobTag, getjobTagListByProId, getjobTagListByUserId, updateJobTag } from '@/api/project'
import { mapGetters, mapMutations } from 'vuex'
import { computeTaskStatus, computedDurTime } from '@/common/js/utils'
import qs from 'qs'
import loadData from '@/base/load'
export default {
  // props: {
  //   curProject: {
  //     type: Object,
  //     default () {
  //       return {}
  //     }
  //   }
  // },
  components: {
    loadData
  },
  data () {
    return {
      // 任务总数
      totalTask: 0,
      // 每页条数
      pageSize: 10,
      // 当前页
      pageNumber: 1,
      labelCon: '',
      logLevel: '',
      tagListWrap: [],
      selectTagId: '',
      stateLevel: '',
      selectStateId: '',
      selectJobTag: '',
      selectTagSameBtn: false,
      taskViewBtn: false,
      // 修改index
      jobTabModifyindex: -1,
      selectedLabelIndex: -1,
      dropTagActive: false,
      dropStateActive: false,
      tagAllSele: true,
      stateAllSele: true,
      taskList: [],
      stateAttr: [
        { id: 'WAITING', jobTag: '等待' },
        { id: 'RUNNING', jobTag: '运行中' },
        { id: 'STOPPED', jobTag: '停止' },
        { id: 'FAILED', jobTag: '失败' },
        { id: 'SUCCEEDED', jobTag: '成功' },
        { id: '', jobTag: '全部' }
      ],
      taskStatus: 'ALL',
      // 表格数据加载
      tableLoad: false,
      // 数据加载过程
      loadState: true
    }
  },
  directives: {
    focus: {
      // 指令的定义
      inserted: function (el) {
        // 聚焦元素
        el.querySelector('input').focus()
      }
    }
  },
  methods: {
    // 跳转或创建tensorboard
    toTensorBoard (row) {
      if (row.tensorboardUrl) {
        window.open('http://' + row.tensorboardUrl, '_blank')
      } else {
        if (row.showTensorBoardLoding === true) {
          return false
        }
        this._createTensorBoard(row)
      }
    },
    composeValue (item, row) {
      return {
        item: item,
        row: row
      }
    },
    // 修改标签
    jobTabModifyFun (row, index) {
      this.jobTabModifyindex = index
      if (row.jobTag) {
        this.labelCon = row.jobTag
      } else {
        this.labelCon = ''
      }
    },
    handleCommand (item, row) {
      if (item.item.jobTag === '全部') {
        this.stateAllSele = true
      } else {
        this.stateAllSele = false
      }
      if (this.selectStateId === item.item.id) {
        this.selectStateId = item.item.id
        this.selectJobTag = item.item.jobTag
        this._getProjectDetail()
      } else {
        this.selectStateId = item.item.id
        this.selectJobTag = item.item.jobTag
        this._getProjectDetail()
      }
    },
    handleCommandTag (command) {
      if (command === '全部') {
        this.tagAllSele = true
      } else {
        this.tagAllSele = false
      }
      if (this.selectTagId === command) {
        return false
      } else {
        this.selectTagId = command
        this._getProjectDetail()
      }
    },
    // 选中标签下拉框
    handleVisibleTag (v) {
      this.dropTagActive = v
    },
    handleVisibleState (v) {
      this.dropStateActive = v
    },
    handlelabelFocusCon (agm) {
      if (this.selectTagId === this.labelCon && this.taskList.length <= 1) {
        this.selectTagSameBtn = true
      } else {
        this.selectTagSameBtn = false
      }
    },
    handlelabelBlueCon (agm) {
      // if (this.labelCon) {
      if (agm.jobTag === this.labelCon) {
        this.selectedLabelIndex = -1
        this.jobTabModifyindex = -1
        return false
      } else {
        if (this.jobTabModifyindex !== -1) {
          this._updateJobTag(agm)
          this.selectedLabelIndex = -1
          this.jobTabModifyindex = -1
        } else {
          this._addTagsFun(agm)
          this.selectedLabelIndex = -1
          this.jobTabModifyindex = -1
        }
      }
    },
    // 点击加号
    handlelabelConAdd (index, row) {
      this.jobTabModifyindex = -1
      if (parseInt(this.selectedLabelIndex) === parseInt(index)) {
        return false
      } else {
        this.labelCon = ''
        this.selectedLabelIndex = index
      }
    },
    cellClickTagfun (row, event, column) {},
    // 点击确定标签更改
    handlelabelConConfirm (parameter) {
      if (this.labelCon) {
        this._addTagsFun(parameter)
        this.selectedLabelIndex = -1
      } else {
        this.$message({ message: '请输入标签内容', showClose: true, type: 'error' })
      }
    },
    // 选择任务状态
    checkTaskStatus (state) {
      this.taskStatus = state
      this.pageNumber = 1
      this._getProjectDetail(state)
    },
    // 分页
    handleSizeChange (val) {
      this.pageSize = val
      this.pageNumber = 1
      this._getProjectDetail()
    },
    handleCurrentChange (val) {
      this.pageNumber = val
      const taskStatusVal = this.taskStatus
      this._getProjectDetail(taskStatusVal)
    },
    // 查看任务所属项目
    toProjectDetail (projectId) {
      this.$router.push({ path: '/project/detail/task', query: { projectid: projectId } })
    },
    // 查看任务
    viewTaskDetail (row) {
      this.$router.push({ path: '/project/task/view/result', query: { taskname: row.jobName, taskid: row.id } })
    },
    // 停止任务
    stopTask (row) {
      this.$confirm('此操作将停止该任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this._taskOperation(row.id, 2)
      })
    },
    // table头部样式
    tableheaderClassName ({ row, rowIndex }) {
      return 'table-head-th'
    },
    spidercellname ({ row, column, rowIndex, columnIndex }) {
      if (this.taskViewBtn) {
        if (columnIndex === 0) {
          return 'spider-cell'
        }
      }
    },
    /*
      -----接口调用-----
    */
    // 创建任务看板
    _createTensorBoard (row) {
      let rowIndex = 0
      this.taskList.map((item, i) => {
        if (item.id === row.id) {
          rowIndex = i
          let tempItem = this.taskList[rowIndex]
          tempItem.showTensorBoardLoding = true
          this.$set(this.taskList, rowIndex, tempItem)
        }
      })
      const data = qs.stringify({
        'jobId': row.id
      })
      createTensorBoard(data).then(res => {
        if (res.message.code === 0) {
          this.$message({ message: '创建成功', showClose: true, type: 'success' })
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
        this._getProjectDetail()
        let tempItem = this.taskList[rowIndex]
        tempItem.showTensorBoardLoding = false
        this.$set(this.taskList, rowIndex, tempItem)
      })
    },
    // 添加标签
    _addTagsFun (parameter) {
      var myProjectId = ''
      if (this.$route.path === '/project/task') {
        myProjectId = parameter.projectId
      } else {
        myProjectId = this.$route.query.projectid
      }
      let data = qs.stringify({
        projectId: myProjectId,
        jobId: parameter.id,
        jobTag: this.labelCon,
        userId: this.userInfo.userId
      })
      saveJobTag(data).then(res => {
        if (res.message.code === 0) {
          this._getProjectDetail()
          this._getjobTagListByProId()
          this.$message({ message: '添加成功', showClose: true, type: 'success' })
        } else {
          this.$message({ message: res.message, showClose: true, type: 'error' })
        }
      })
    },
    // 修改标签
    _updateJobTag (parameter) {
      var myProjectId = ''
      if (this.$route.path === '/project/task') {
        myProjectId = parameter.projectId
      } else {
        myProjectId = this.$route.query.projectid
      }
      let data = qs.stringify({
        projectId: myProjectId,
        jobId: parameter.id,
        jobTag: this.labelCon
      })
      updateJobTag(data).then(res => {
        if (res.message.code === 0) {
          this.$message({ message: '修改成功', showClose: true, type: 'success' })
          if (this.selectTagSameBtn) {
            this.selectTagId = this.labelCon
          }
          this._getProjectDetail()
          this._getjobTagListByProId()
        } else {
          this.$message({ message: res.message, showClose: true, type: 'error' })
        }
      })
    },
    // 获取标签
    _getjobTagListByProId (jobName, operateType) {
      if (this.$route.path === '/project/task') {
        let para = `?userId=${this.userInfo.userId}`
        getjobTagListByUserId(para).then(res => {
          if (res.message.code === 0) {
            this.tagListWrap = res.data
            var tagAllObj = {}
            tagAllObj.jobTag = '全部'
            this.tagListWrap.push(tagAllObj)
          } else {
            this.$message({ message: res.message.message, showClose: true, type: 'error' })
          }
        })
      } else {
        let para = `?projectId=${this.$route.query.projectid}`
        getjobTagListByProId(para).then(res => {
          if (res.message.code === 0) {
            this.tagListWrap = res.data
            var tagAllObj = {}
            tagAllObj.jobTag = '全部'
            this.tagListWrap.push(tagAllObj)
          } else {
            this.$message({ message: res.message.message, showClose: true, type: 'error' })
          }
        })
      }
    },
    // 查询任务
    _getProjectDetail (state) {
      let apiMethod = ''
      let para = ''
      var states = ''
      if (state) {
        states = state
      } else {
        states = this.taskStatus
      }
      if (this.$route.path === '/project/task') {
        let statePara = ''
        if (states) {
          statePara = (states === 'ALL') ? '' : states
        }
        this.taskViewBtn = false
        if (this.selectTagId === '全部') {
          para = `?taskStatus=${statePara}&pageNumber=${this.pageNumber}&pageSize=${this.pageSize}&jobTag=`
        } else {
          para = `?taskStatus=${statePara}&pageNumber=${this.pageNumber}&pageSize=${this.pageSize}&jobTag=${this.selectTagId}`
        }
        apiMethod = getTaskViewList
      } else {
        this.taskViewBtn = true
        if (this.selectTagId === '全部') {
          para = `?cp=${this.pageNumber}&ps=${this.pageSize}&projectId=${this.$route.query.projectid}&jobTag=&taskStatus=${this.selectStateId}`
        } else {
          para = `?cp=${this.pageNumber}&ps=${this.pageSize}&projectId=${this.$route.query.projectid}&jobTag=${this.selectTagId}&taskStatus=${this.selectStateId}`
        }
        apiMethod = getProjectDetail
      }
      this.tableLoad = true
      apiMethod(para).then(res => {
        this.tableLoad = false
        this.loadState = false
        if (res.message.code === 0) {
          this.totalTask = res.data.total
          this.taskList = res.data.list
          this.taskList && this.taskList.map(item => {
            // 处理备注内容
            if (item.remark) {
              const reg1 = new RegExp('<p>', 'g')
              const reg2 = new RegExp('</p>', 'g')
              const reg3 = new RegExp('<br>', 'g')
              item.remark = item.remark.replace(reg1, '').replace(reg2, '').replace(reg3, '\n')
            }
            let createdTime = item.createdTime ? item.createdTime : item.createTime
            let computedStatus = computeTaskStatus({ state: item.state, executionType: item.executionType })
            item.duration = computedDurTime(item.timeConsuming)
            // item.duration = computedDuration(createdTime, item.completedTime)
            // if (item.state === 'RUNNING' && item.executionType !== 'STOP' && item.completedTime === 0) item.duration = computedDuration(createdTime, Date.now())
            item.createdTime = createdTime
            item.status = computedStatus.val
            item.statusClass = computedStatus.className
          })
          let jobNumber = Number(res.data.total) + 1
          this.storeJobcode(jobNumber)
          if (this.taskList && this.taskList.length > 0) {
            const taskNo = this.taskList[0].codeNo
            this.$emit('update-taskno', taskNo)
          }
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    // 任务操作
    _taskOperation (jobId, operateType) {
      let para = `?jobId=${jobId}&operateType=${operateType}`
      taskOperation(para).then(res => {
        if (res.message.code === 0) {
          this._getProjectDetail()
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    ...mapMutations({
      storeTask: 'SET_CUR_TASK',
      storeProject: 'SET_CUR_PROJECT',
      storeTaskFromHome: 'SET_TASK_FROM_HOME',
      storeJobcode: 'SET_JOB_CODENO'
    })
  },
  computed: {
    isTaskView: function () {
      let path = this.$route.path
      return path === '/project/task'
    },
    ...mapGetters([
      'curProject',
      'taskFromHome',
      'userInfo'
    ])
  },
  created () {
    this._getjobTagListByProId()
  },
  mounted () {
    if (this.taskFromHome.state) {
      this.checkTaskStatus(this.taskFromHome.state)
      this.taskStatus = this.taskFromHome.state
      this.taskFromHome.state = ''
      this.storeTaskFromHome('')
    } else {
      this._getProjectDetail()
      // this._getjobTagListByProId()
    }
  }
  // watch: {
  //   curProject: function (newVal, oldVal) {
  //     this._getProjectDetail()
  //   }
  // }
}
</script>

<style lang="stylus">
.project-task-box
  .header-tabs
    padding 20px 0
    display flex
    align-items center
    justify-content space-between
    user-select none
    .category-item
      display inline-block
      font-size 14px
      color #8D9091
      color #555
      margin-right 22px
      cursor pointer
      &:hover
        color #2196f3
    .active-category
      color #2196f3
    .count
      font-size 12px
      color #8d9091
  .project-task
    background #ffffff
    border-radius 5px
    margin-bottom 20px
    .task-table
      .name-wrapper
        display inline
      .cell
        height 23px
        padding 0 10px
      .spider-box
        padding-top 1px
        img
          width 12px
          height 12px
      .el-table th div.cell
        padding 0 10px
      .el-table th div
        padding 0
      .el-select
        height 23px
        .el-input__inner
          height 23px
          border none
          background transparent
          padding-left 0
      .el-input__icon
        line-height 23px
      .el-table th div
        line-height 23px
      .task-time
        display inline-block
        min-width 52px
        text-align center
      .table-link
        overflow hidden
        text-overflow ellipsis
        white-space nowrap
        font-weight 600
        .label-con-modify
          cursor pointer
        .label-con-add
          width 39px
          height 22px
          line-height 22px
          border 1px dotted #D1D1D2
          text-align center
          color #333333
          cursor pointer
        .label-con-box
          display flex
          .el-input
            width 110px
          .el-input__inner
            padding 0 10px
            font-size 14px
            line-height 22px
            height 22px
            border 1px solid #D1D1D2
            border-radius 3px
          .label-con-true
            width 25px
            height 22px
            line-height 22px
            text-align center
            cursor pointer
      .table-link-tag
        font-weight normal
    .status-box
      border-radius 5px
      padding 4px 8px 2px
      font-size 12px
      line-height 17px
      color #ffffff
    .status-success
      background #0ECC78
    .status-run
      background #309EEC
    .status-wait
      background #FFBB41
    .status-stop
      background #A7ACB5
    .status-failure
      background #F5654A
    .table-action
      color #4285f4
      cursor pointer
      margin-right 10px
    .table-action-disable
      span
        color #ebeef5
.tagdropdown
  .tag-active-class,.tag-all-sele
    color #1890ff
.statedropdown
  .state-active-class,.state-all-sele
    color #1890ff
.state-dropdown
  min-width 120px
  .state-all-bottom
    border-top 1px solid #B1B5B7
.tag-dropdown
  min-width 158px
  .tag-dropdown-boxs
    max-height 180px
    overflow-x hidden
    overflow-y scroll
  .tag-dropdown-box
    .tag-all-bottom
      border-top 1px solid #B1B5B7
.task-remark-popover
  word-break break-all
.el-dropdown-menu
  padding-bottom 0
</style>
